package com.patsnap.data.npd.dw.schema.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.patsnap.data.npd.dw.handler.TimestampLongTypeHandler;
import com.patsnap.data.npd.dw.common.compress.ByteBufferAdapter;
import com.patsnap.one.etl.table.dto.MybatiesDto;
import com.patsnap.one.etl.table.dto.SourceTableDto;
import com.patsnap.one.etl.table.dto.TargetTableDto;
import com.patsnap.one.etl.table.meta.annotation.FieldMeta;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.apache.ibatis.type.JdbcType;

import java.nio.ByteBuffer;
import java.sql.JDBCType;

@Data
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class BaseNonePatentDto implements SourceTableDto, TargetTableDto, MybatiesDto {
    /**
     * 更新时间
     */
    @FieldMeta(fieldName = "updated_ts", jdbcType = JDBCType.TIMESTAMP, comment = "更新时间")
    @TableField(value = "updated_ts",
            jdbcType = JdbcType.TIMESTAMP,
            updateStrategy = FieldStrategy.NEVER,
            insertStrategy = FieldStrategy.NEVER,
            typeHandler = TimestampLongTypeHandler.class)
    private Long updatedTs;

    /**
     * 创建时间
     */
    @FieldMeta(fieldName = "created_ts", jdbcType = JDBCType.TIMESTAMP, comment = "创建时间")
    @TableField(value = "created_ts",
            jdbcType = JdbcType.TIMESTAMP,
            updateStrategy = FieldStrategy.NEVER,
            insertStrategy = FieldStrategy.NEVER,
            typeHandler = TimestampLongTypeHandler.class)
    private Long createdTs;

    /**
     * get gsoner
     */
    public static synchronized Gson createGSoner() {
        return new GsonBuilder()
                .registerTypeHierarchyAdapter(ByteBuffer.class, new ByteBufferAdapter())
                .setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();
    }

    public String toString(boolean isJsonPretty) {
        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(ByteBuffer.class, new ByteBufferAdapter())
                .setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .disableHtmlEscaping().create();
        String body = gson.toJson(this);
        if (isJsonPretty) {
            JSONObject json = JSON.parseObject(body);
            body = JSON.toJSONString(json, isJsonPretty);
        }
        return body;
    }
}
